package com.awesome.videodemo.record.record4;

import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;

import com.awesome.common.base.mvp.BaseActivity;
import com.awesome.common.constant.Constant;
import com.awesome.common.util.log.ShowLogUtil;
import com.awesome.videodemo.R;
import com.awesome.videodemo.record.record4.CameraPreview;

import java.io.File;
import java.io.IOException;

/**
 * Author: zhangjingfang
 * Email:zhangjingfang@jeejio.com
 * Date: 2021/10/20
 * Description:类描述
 */
public class RecordActivity4 extends BaseActivity {
    private Button mBtn;
    private FrameLayout mLayoutPreview;
    private Camera mCamera;
    private com.awesome.videodemo.record.record4.CameraPreview mPreview;
    private MediaRecorder mMediaRecorder;
    private boolean isRecording = false;

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);
        mBtn = findViewById(R.id.button_capture);
        mLayoutPreview = findViewById(R.id.camera_preview);
        // 创建Camera实例
        mCamera = getCameraInstance();
        // 创建预览视图，并作为Activity的内容
        mPreview = new CameraPreview(this, mCamera);
        mLayoutPreview.addView(mPreview);
        if (!hasPermission(Constant.WRITE_EXTERNAL_PERMISSION)) {
            requestPermission(Constant.WRITE_EXTERNAL_CODE, Constant.WRITE_EXTERNAL_PERMISSION);
        }
        if (!hasPermission(Constant.CAMERA_PERMISSION)) {
            requestPermission(Constant.CAMERA_CODE, Constant.CAMERA_PERMISSION);
        }
        if (!hasPermission(Constant.RECORD_AUDIO_PERMISSION)) {
            requestPermission(Constant.RECORD_AUDIO_CODE, Constant.RECORD_AUDIO_PERMISSION);
        }
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                record();
            }
        });
    }

    private void record(){
        if (isRecording) {
            // stop recording and release camera
            mMediaRecorder.stop();  // stop the recording
            releaseMediaRecorder(); // release the MediaRecorder object
            mCamera.lock();         // take camera access back from MediaRecorder

            // inform the user that recording has stopped
            mBtn.setText("Capture");
            isRecording = false;
        } else {
            // initialize video camera
            if (prepareVideoRecorder()) {
                // Camera is available and unlocked, MediaRecorder is prepared,
                // now you can start recording
                mMediaRecorder.start();

                // inform the user that recording has started
                mBtn.setText("Stop");
                isRecording = true;
            } else {
                // prepare didn't work, release the camera
                releaseMediaRecorder();
                // inform user
            }
        }
    }

    private boolean prepareVideoRecorder() {

        if(mCamera == null){
            mCamera = getCameraInstance();
        }
        mMediaRecorder = new MediaRecorder();

        // Step 1: Unlock and set camera to MediaRecorder
        mCamera.unlock();
        mMediaRecorder.setCamera(mCamera);

        // Step 2: Set sources
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
        mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

        // Step 4: Set output file
        mMediaRecorder.setOutputFile(getOutputMediaFile());

        // Step 5: Set the preview output
        mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

        // Step 6: Prepare configured MediaRecorder
        try {
            mMediaRecorder.prepare();
        } catch (IllegalStateException e) {
            ShowLogUtil.info("IOException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            ShowLogUtil.info("IOException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        }
        return true;
    }

    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            // 在多个摄像头时，默认打开后置摄像头
            c = Camera.open();
            // Android 2.3（API 9之后可指定cameraId摄像头id，可选值为后置（CAMERA_FACING_BACK）/前置（ CAMERA_FACING_FRONT）
            //  c = Camera.open(cameraId);
        } catch (Exception e){
            // Camera被占用或者设备上没有相机时会崩溃。
        }
        return c;  // returns null if camera is unavailable
    }

    /**
     * 获取视频保存路径
     */
    public String getOutputMediaFile(){
        return Environment.getExternalStorageDirectory().getPath()+ File.separator+"test.mp4";
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();   // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }
} 
 
 